# _*_ coding: utf-8 _*_
import os
import threading
import queue
from PyQt5 import QtCore
from requests.exceptions import  RequestException
from .counter import Counter
from .spider import NovelSpider

class NovelThread(threading.Thread):
    # 更新同步锁
    _updateLock = threading.Lock()
    # 线程结束信号
    endFlag = False
    def __init__(self, dataQueue: queue.Queue, counter: Counter,
                 statusSignal: QtCore.pyqtSignal, progressSignal: QtCore.pyqtSignal,
                 toDir: str):
        '''
        :param dataQueue: 小说信息队列集
        :param counter: 计数器
        :param statusSignal: 状态栏信号
        :param progressSignal: 进度条信号
        :param toDir: 小说存储路径
        '''
        super(NovelThread, self).__init__()
        self.dataQueue = dataQueue
        self.counter = counter
        self.statusSignal = statusSignal
        self.progressSignal = progressSignal
        self.toDir = toDir

        # 爬虫对象
        self._spider = NovelSpider()

    def run(self):
        while NovelThread.endFlag:
            try:
                infos = self.dataQueue.get(block=False)
            except queue.Empty:
                pass
            else:
                self.download(infos)
                self.updateSignal(infos[1])
                self.dataQueue.task_done()


    def stop(self) -> None:
        '''结束线程'''
        NovelThread.endFlag = False


    def updateSignal(self, msg: str):
        '''更新信号'''
        with self._updateLock:
            self.statusSignal.emit(f"当前任务 => {msg}")
            try:
                self.progressSignal.emit(next(self.counter))
            except StopIteration:
                pass


    def download(self, infos) -> None:
        '''下载'''
        try:
            self._spider.url = infos[-1]
            self._spider.sendGet()
        except RequestException:
            self.dataQueue.put(infos)
        else:
            context = self._spider.parse()
            # 路径
            filepath = os.path.join(self.toDir, f"{infos[0]}.txt")
            with open(filepath, "w", encoding="utf-8") as fp:
                # 写入小说标题
                fp.write(f"{infos[1]}\n")
                for line in context:
                    fp.write(line)